package com.ruoyi.basedata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.basedata.domain.*;
import com.ruoyi.basedata.mapper.*;
import com.ruoyi.basedata.service.IRoomService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SnowflakeUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 楼栋房间Service业务层处理
 *
 * @author ruoyi
 * @date 2023-09-07
 */
@Service
@Slf4j
public class RoomServiceImpl implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private TerminalsXbMapper terminalsXbMapper;

    @Autowired
    private TerminalsDbMapper terminalsDbMapper;

    @Autowired
    private ReplaceMapper replaceMapper;

    @Autowired
    private TransferMapper transferMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private LouDongMapper louDongMapper;


    /**
     * 查询楼栋房间
     *
     * @param ID 楼栋房间主键
     * @return 楼栋房间
     */
    @Override
    public Room selectRoomByID(Long ID) {
        return roomMapper.selectRoomByID(ID);
    }

    /**
     * 查询楼栋房间列表
     *
     * @param room 楼栋房间
     * @return 楼栋房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增楼栋房间
     *
     * @param room 楼栋房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        List<Room> rooms = roomMapper.selectList(new LambdaQueryWrapper<Room>()
                .eq(Room::getLdId, room.getLdId())
                .eq(Room::getRoomName, room.getRoomName()));
        if (null != rooms && rooms.size() > 0) {
            return 0;
        }
        SnowflakeUtils snowflakeUtils = new SnowflakeUtils(0, 0);
        long id = snowflakeUtils.nextId();
        room.setRoomId(String.valueOf(id));
        room.setDeleteMark(0);
        room.setTerminalType(2);
        return roomMapper.insertRoom(room);
    }

    /**
     * 修改楼栋房间
     *
     * @param room 楼栋房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        return roomMapper.updateRoom(room);
    }

    /**
     * 批量删除楼栋房间
     *
     * @param IDs 需要删除的楼栋房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIDs(Long[] IDs) {
        List<Room> rooms = roomMapper.selectBatchIds(Arrays.asList(IDs));
        List<Long> deleteList = new ArrayList<>();
        rooms.forEach(room -> {
            if (room.getTerminalType() == 1) {
//                List<TerminalsDb> terminalsDbs = terminalsDbMapper.selectList(new LambdaQueryWrapper<TerminalsDb>()
//                        .eq(room.getRoomId() != null, TerminalsDb::getRoomId, room.getRoomId()));
//                if (terminalsDbs.size() == 0) {
//                    deleteList.add(room.getID());
//                }
            }
//            if (room.getTerminalType() == 2){
//                 List<TerminalsXb> terminalsXbs = terminalsXbMapper.selectList(new LambdaQueryWrapper<TerminalsXb>()
//                        .eq(room.getRoomId() != null, TerminalsXb::getRoomId, room.getRoomId()));
//                 if (terminalsXbs.size() == 0){
//                     deleteList.add(room.getID());
//                 }
//            }
        });
        if (deleteList.size() == 0) {
            return 0;
        }
        return roomMapper.deleteBatchIds(Arrays.asList(IDs));
    }

    /**
     * 删除楼栋房间信息
     *
     * @param ID 楼栋房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByID(Long ID) {
        return roomMapper.deleteById(ID);
    }

    @Override
    public List<Room> selectRoomListByAreaCode(String areaCode) {
        return roomMapper.selectRoomListByAreaCode(areaCode);
    }

    @Override
    @Transactional
    public String BoundTerminal(Room room) {
        TerminalsXb terminalsXb = terminalsXbMapper.selectOne(new LambdaQueryWrapper<TerminalsXb>());
//                .eq(TerminalsXb::getTerminalId, room.getTerminalId()));

        if (terminalsXb == null) {
            return "请选择一个设备绑定房间";
        }
//         if (terminalsXb.getRoomId()!=null && !terminalsXb.getRoomId().equals("") ){
//             return "该设备已绑定房间请刷新页面";
//         }else {
//             terminalsXb.setRoomId(room.getRoomId());
//             terminalsXb.setLdId(room.getLdId());
        if (room.getUserID() != null) {
            terminalsXb.setUserId(room.getUserID());
        }
        terminalsXbMapper.updateTerminalsXb(terminalsXb);
        room.setTerminalType(2);
        room.setTerminalID(terminalsXb.getTerminalId());
        roomMapper.updateRoom(room);
        return "绑定成功";
//         }
    }

    @Override
    @Transactional
    public String BoundUser(Room room) {
        Room room1 = roomMapper.selectRoomByID(room.getID());
        //如果room的userId不为空说明已绑定
        if (room1.getUserID() != null && !room1.getUserID().equals("")) {
            return "该房间已绑定用户请刷新页面";
        }
        if (room.getUserID() == null) {
            return "请选择一个用户绑定房间";
        } else {
            roomMapper.updateRoom(room);
            //判断该房间是否已经绑定设备，绑定了需要更新设备表
//            if (room.getTerminalId()!=null && !room.getTerminalId().equals("")){
//                TerminalsXb terminalsXb = terminalsXbMapper.selectOne(new LambdaQueryWrapper<TerminalsXb>()
//                        .eq(TerminalsXb::getTerminalId, room.getTerminalId()));
//                terminalsXb.setUserId(room.getUserID());
//                terminalsXbMapper.updateTerminalsXb(terminalsXb);
//            }
            return "绑定成功";
        }
    }

    //换表
    @Override
    @Transactional
    public String changeTerminalXb(Room room) {
        if (room.getNewTerminalId() == null) {
            return "请先选择一个设备";
        }
        TerminalsXb oldTerminalsXb = terminalsXbMapper.selectOne(new LambdaQueryWrapper<TerminalsXb>()
                .eq(TerminalsXb::getTerminalId, room.getOldTerminalId())
                .eq(TerminalsXb::getDelFlag, 0));
        TerminalsXb newTerminalsXb = terminalsXbMapper.selectOne(new LambdaQueryWrapper<TerminalsXb>()
                .eq(TerminalsXb::getTerminalId, room.getNewTerminalId())
                .eq(TerminalsXb::getDelFlag, 0));
        Room room1 = roomMapper.selectRoomByID(room.getID());

        //新旧设备不能为空，根据roomid查看当前房间是否的设备编号和请求更换的旧设备是否一致，防止在此期间其他任做换表操作，表状态必须正常，新旧设备不能一样
        if (oldTerminalsXb == null) {
            return "该房间当前绑定的表不存在";
        }
        if (newTerminalsXb == null) {
            return "您选择更换的设备不存在，请刷新页面";
        }
//        if(!room1.getTerminalId().equals(room.getOldTerminalId())){
//            return "该房间当前所绑定的表和您请求更换的的旧表不一致，请刷新页面";
//        }
        if (newTerminalsXb.getTerminalMark() == null || newTerminalsXb.getTerminalMark() == 0) {
            return "请选择表状态正常的表来做更换";
        }
        if (room.getNewTerminalId().equals(room.getOldTerminalId())) {
            return "当前房间所绑定的表和您选择更换的表一致";
        }
        oldTerminalsXb.setChangeMark(1);
//        oldTerminalsXb.setRoomId("");
        terminalsXbMapper.updateTerminalsXb(oldTerminalsXb);
//        newTerminalsXb.setRoomId(room.getRoomId());
//        newTerminalsXb.setLdId(room.getLdId());
        if (room.getUserID() != null) {
//            newTerminalsXb.setUserId(room.getUserID());
        }
        terminalsXbMapper.updateTerminalsXb(newTerminalsXb);
        room.setTerminalID(newTerminalsXb.getTerminalId());
        roomMapper.updateRoom(room);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Replace replace = Replace.builder().tenantId(newTerminalsXb.getTenantId()).changeTime(new Date()).terminalClassify(2)
                .oldTerminalId(oldTerminalsXb.getTerminalId()).newTerminalId(newTerminalsXb.getTerminalId())
                .newBaseReading(newTerminalsXb.getBaseReading()).oldSettlementReading(oldTerminalsXb.getBaseReading())
                .operator(loginUser.getUsername()).remark(room.getChangeTerminalRemark()).build();
        replaceMapper.insertReplace(replace);

        return "换表成功";
    }

    @Override
    @Transactional
    public String changeUser(Room room) {
        Room room1 = roomMapper.selectRoomByID(room.getID());
        if (!room1.getUserID().equals(room.getOldUserId())) {
            return "该房间当前绑定的用户和您请求的旧用户不一致，请刷新页面";
        }
        if (room.getNewUserId() == null) {
            return "请选择一个用户";
        }
        if (room.getOldUserId().equals(room.getNewUserId())) {
            return "新旧用户不能一样";
        }


//        room.setUserId(room.getNewUserId());
        roomMapper.updateRoom(room);
        Transfer build = Transfer.builder().ghTime(new Date()).newUserid(room.getNewUserId()).oldUserid(room.getOldUserId()).tenantId(room.getTenantId()).build();
        transferMapper.insertTransfer(build);
        return "过户成功";
    }

    @Override
    public List<Room> selectListByLdId(String treeLdId) {
        return roomMapper.selectListByLdId(treeLdId);
    }

    @Override
    @Transactional
    public boolean cancelTerminal(TerminalsXb terminalsXb) {
        terminalsXb.setTerminalMark(0);
        int i = terminalsXbMapper.updateTerminalsXb(terminalsXb);
        Account account = Account.builder().build();
//                .roomId(terminalsXb.getRoomId()).TerminalID(terminalsXb.getTerminalId())
//                .ldId(terminalsXb.getLdId()).createTime(new Date()).Operator(getUsername())
//                .UserID(terminalsXb.getUserID()).tenantId(terminalsXb.getTenantId()).build();
        final int flag = accountMapper.insertAccount(account);
        return flag != 0 && i != 0;
    }

    @Override
    public List<Room> selectRoomList2(Room room) {
        return roomMapper.selectRoomList2(room);
    }

    @Override
    public List<Room> selectRoomListlistByLd(String ldId) {
        return roomMapper.selectList(new LambdaQueryWrapper<Room>()
                .eq(Room::getLdId, ldId));
    }

    @Override
    public String importData(List<Room> list, boolean updateSupport, String operName) {
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入房间数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Room room : list) {
            try {
                // 验证区域下有无该楼栋
                LouDong louDong = louDongMapper.selectOne(new LambdaQueryWrapper<LouDong>()
                        .eq(LouDong::getAreaCode, room.getAreaCode())
                        .eq(LouDong::getLdName, room.getLdName()));
                if (louDong == null) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、楼栋名称 " + room.getLdName() + " 不存在");
                } else {
                    List<Room> rooms = roomMapper.selectList(new LambdaQueryWrapper<Room>()
                            .eq(Room::getLdId, louDong.getLdId())
                            .eq(Room::getRoomName, room.getRoomName()));
                    if (null != rooms && rooms.size() > 0) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、房间名称 " + room.getRoomName() + " 已存在");
                    } else {
                        SnowflakeUtils snowflakeUtils = new SnowflakeUtils(0, 0);
                        long id = snowflakeUtils.nextId();
                        room.setLdId(louDong.getLdId());
                        room.setRoomId(String.valueOf(id));
                        room.setDeleteMark(0);
                        room.setTerminalType(2);
                        roomMapper.insertRoom(room);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、房间名称 " + room.getRoomName() + " 导入成功");
                    }
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、房间名称 " + room.getRoomName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


}
